package jflowmap.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.geom.Point2D;

import jflowmap.util.piccolo.PNodes;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
import edu.umd.cs.piccolo.nodes.PText;

public class PHelp extends PNode {
	private final PText text;
	private static final Font HELP_FONT = new Font("Arial", Font.BOLD, 14);
	private boolean active;
	
	public PHelp () {
		this.text = new PText();
		this.text.setFont(HELP_FONT);
		this.active = true;
		addChild(this.text);
		setVisible(false);
	}
	
	public void activate () {
		active = true;
	}
	
	public void deactivate () {
		active = false;
	}
	
	public void setText (String helpText) {
		text.resetBounds();
		text.setText(helpText);
	}

	public void at(Point2D position) {
		if (position.getX() > text.getWidth())
			position.setLocation(position.getX()+15-text.getWidth(), position.getY());
		else
			position.setLocation(position.getX()+15, position.getY());
		if (position.getY() > 200)
			position.setLocation(position.getX(), position.getY()-18);
		else
			position.setLocation(position.getX(), position.getY()+18);
		PNodes.setPosition(this, position);
		PNodes.setPosition(text, position);
		this.moveToFront();
	}
	
	public void helpFor (PNode node, final HelpTextSwitcher hts) {
		node.addInputEventListener(new PBasicInputEventHandler() {
			@Override
			public void mouseClicked(PInputEvent event) {
				setVisible(false);
			}
			
			@Override
			public void mouseEntered(PInputEvent event) {
				text.setText(hts.getHelpText());
	    		setVisible(active);
	    		at(event.getCanvasPosition());
			}
			
			@Override
			public void mouseMoved(PInputEvent event) {
				setVisible(active);
				if (text.getText() != hts.getHelpText()) {
					text.setText(hts.getHelpText());
				}
	    		at(event.getCanvasPosition());
			}
			
			@Override
			public void mouseExited(PInputEvent event) {
				setVisible(false);
			}
		});
	}
}
